package com.example.demo1115.interceptors;

import com.alibaba.fastjson.JSON;
import com.example.demo1115.util.JwUtil;
import com.example.demo1115.vo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if(StringUtils.hasText(token)){
            if(JwUtil.verifyToken(token)){
                return true;
            }
        }
        PrintWriter writer = response.getWriter();
        Result result=new Result(500,"未登录");
        String jsonString = JSON.toJSONString(result);
        writer.print(jsonString);
        writer.flush();
        writer.close();
        return false;
    }
}
